var credit = {
    baseUrl: "/scsp",
    formId :"creditProgramForm",
    scspId:"",
    custId:"",
    floatRate:"",
    stat:"",
    grantTerm:"",
    rateAdjustDate:""
}
var msg="";
layui.use(['form','layer','laydate'],function () {
    var layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form;
    var laydate = layui.laydate;
    // initTimePickers("startDate");
    laydate.render({
        elem: '#startDate', //指定元素
        min: minDate(),
        done: function(value, date, endDate){
            if(value != ""){
                var array = value.split("-");
                var date = new Date(array[0],array[1]-1,array[2]);
                $("#endDate").val( formatDate(date));
                //如果贷款期限不为空则自动计算到期日
                var TermY = $("#grantTermY").val();
                var TermM = $("#grantTermM").val();
                var TermD = $("#grantTermD").val();
                var allDateY = "";
                var allDateM = "";
                var allDateD = "";
                if(TermY != ""){
                    allDateY =  parseInt($("#endDate").val().split("-")[0]) + parseInt(TermY);//计算年
                }
                if(TermM != ""){
                    allDateM =  parseInt($("#endDate").val().split("-")[1]) + parseInt(TermM);//计算月
                    if(parseInt(TermM) + parseInt($("#endDate").val().split("-")[1]) < 10){
                    allDateM = "0"+allDateM;
                    }
                }
                if(TermD != ""){
                    if(parseInt(allDateM)== 2 || parseInt(allDateM)== 4 || parseInt(allDateM)== 6 || parseInt(allDateM)== 9 || parseInt(allDateM)== 11){
                        if(parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) >30){
                            allDateD =  parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 30;//计算日
                            if((parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 30) < 10){
                                allDateD  = "0"+(parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 30)
                            }
                            allDateM = parseInt(allDateM)+1;
                           if(parseInt(allDateM) >12){
                               allDateM = parseInt(allDateM) - 12;
                               if(parseInt(allDateM) < 10){
                                   allDateM = "0"+parseInt(allDateM)
                               }
                               allDateY = parseInt(allDateY)+1;

                           }
                        }else{
                            allDateD =  parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) ;//计算日
                        }
                    }else{
                        if(parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) >31){
                            allDateD =  parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 31;//计算日
                            if((parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 31) < 10){
                                allDateD  = "0"+(parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) - 31)
                            }
                            allDateM = parseInt(allDateM)+1;
                            if(parseInt(allDateM) >12){
                                allDateM = parseInt(allDateM) - 12;
                                if(parseInt(allDateM) < 10){
                                        allDateM = "0"+parseInt(allDateM)
                                }
                                allDateY = parseInt(allDateY)+1;
                            }
                        }else{
                            allDateD =  parseInt($("#endDate").val().split("-")[2]) + parseInt(TermD) ;//计算日
                        }
                    }

                }
                $("#endDate").val(allDateY+"-"+allDateM+"-"+allDateD);
                //放款日期变更时 若还款方式为“0：借款日为还款日”，则改变还款日的值
                if($("#repaymentDateWay").val() == "0"){
                    var array = value.split("-");
                    if(array[2].indexOf("0") != -1){
                        $("#repaymentDate").val(array[2].charAt(1));
                    }else{
                        $("#repaymentDate").val(array[2]);
                    }
                    $("#repaymentDate").attr("readonly","readonly");
                }
            }else{
            	$("#endDate").val('');
            }
        },
        change: function(value, date, endDate){
        }
    });
    //验证和联动变动事件绑定
    eventBind();
    credit.scspId = getUrlParam("scspId")||""; //获取url的scsp_id
    credit.stat = getUrlParam("stat")||"";//获取状态参数   0：流程查看  1:流程编辑  2：任务编辑 3：任务查看 4：客户经理确认
    if(credit.stat=='0'||credit.stat=='3'){    	
        $("a").hide();
        $("select").attr('disabled','true');
        $("input").attr('readonly','true');
        $("input").attr('disabled','true');
        $('.print_save').hide();
        $('.redAble').hide();
    }else if(credit.stat=='4'){
    	$("a").hide();
    	$('.redAble').show();
    	$('.red').hide();
        $("select").attr('disabled','true');
        $("input").attr('readonly','true');
    	$('.layui-input').removeAttr('readonly');
    	$('.editAble').removeAttr('readonly');
    }else{
    	$('.redAble').hide();
    }
    //初始化数据
    init(credit.scspId);
    //保存事件
    $("#btnCommit").on('click', function() {
        saveData();
    });

});
// 设置最小可选的日期
function minDate(){
    var now = new Date();
    return now.getFullYear()+"-" + (now.getMonth()+1) + "-" + now.getDate();
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
//保存
function saveData() {
    var flag = checkRequiredItems();
    if(!flag){
        return;
    }
    //保存时去掉 还款间隔 下拉框的disabled属性
    $("#repaymentInterval").removeAttr("disabled");
    //拼接利率调整日期
    var rateAdjustDate = "";
    if($("#rateCycle").val() == 3){
        rateAdjustDate = $("#rateAdjustDateM").val()+","+$("#rateAdjustDateD").val();
        $("#rateAdjustDate").val(rateAdjustDate);
    }else{
        $("#rateAdjustDate").val("");
    }
    //拼接贷款期限
    var grantTermY = $("#grantTermY").val();
    var grantTermM = $("#grantTermM").val();
    var grantTermD = $("#grantTermD").val();
    var grantTerm = "";
    if(grantTermY){
        grantTerm = grantTermY;
    }else{
        grantTerm = "0";
    }
    if(grantTermM){
        grantTerm = grantTerm+","+grantTermM;
    }else{
        grantTerm = grantTerm+",0";
    }
    if(grantTermD){
        grantTerm = grantTerm+","+grantTermD;
    }else{
        grantTerm = grantTerm+",0";
    }
    $("#grantTerm").val(grantTerm); //贷款期限
    //月利率
    var executeRate = $("#executeRate").val();
    $("#monthRate").val(parseFloat((parseFloat(executeRate)*10/12)).toFixed(2));
    if($("#rateFloat").val().trim()==''){
    	$("#rateFloat").val('0');
    }
    //利率浮动率
    if($("#rateFloat").val().trim()==''){
    	$("#rateFloat").val('0');
    }
    //利率浮动值
    if($("#rateFloatValue").val().trim()==''){
    	$("#rateFloatValue").val('0');
    }
    //行业投向
    var hytxs=new Array();
    //贷款种类
    var loanTypes = new Array();
    if($("#hytx1").val()){
    	hytxs[0]=$("#hytx1").val();
    	if($("#hytx2").val()){
    		hytxs[1]=$("#hytx2").val();
    		if($("#hytx3").val()){
    			hytxs[2]=$("#hytx3").val();
    			if($("#hytx4").val()){
    				hytxs[3]=$("#hytx4").val();
    				if($("#hytx5").val()){
    					hytxs[4]=$("#hytx5").val();
    				}
    			}
    		}
    	}
    }
    if($("#loanType1").val()){
        loanTypes[0]=$("#loanType1").val();
        if($("#loanType2").val()){
            loanTypes[1]=$("#loanType2").val();
        }
    }
    $("#hytx").val(hytxs.join(','));
    $("#loanType").val(loanTypes.join(','))
    $.ajax({
        url: credit.baseUrl + "/credit",
        type: "put",
        dataType: "json",
        data:JSON.stringify($("#"+credit.formId).serializeObject()),
        contentType: "application/json",
        success: function (data) {
            if (data.code == "200") {
                //保存成功后刷新页面
            	layer.msg(data.message, {icon: 6});
            }else{
            	layer.msg(data.message, {icon: 5});
            }
        }
    });
}
function initDic(data) {
    var dicJson = {
        "repaymentWay": "REPAY_TYPE",//还款方式
        "repaymentInterval": "REPAY_INTERVAL",//还款间隔
        "rateCycle": "RATE_ADJUST_WAY",//利率调整方式
        "singleRateSign": "SINGLE_RATE_SIGN",//单复利率标志
        "loanerAttribute": "LOANER_ATTRIBUTE",//借款人属性
        "guaranteeWay": "WARRANT",//主担保方式
        "warrantWay": "GURARNTEE_MODE",//从担保方式
        "gracePeriodWay": "GRACE_PERIOD_WAY",//宽限期方式
        "loanPurpose": "LOAN_PURPOSE",//贷款用途
        "loanType1":"LOAN_TYPE",//贷款品种
        "loanType2": data.loanTypes[0],
        "gracePeriodSign":"sfdsf_type", //宽限期计息标志 1-是  0-否
        "defaultInterestFloatWay":"FXFloatWay", //罚息浮动率
        "repaymentDateWay":"repaymentDateWay", //还款日确定方式
        "hytx1": "PURPOSE",
        "hytx2": data.hytxs[0],
        "hytx3": data.hytxs[1],
        "hytx4": data.hytxs[2],
        "hytx5": data.hytxs[3]
    };
    selectOnloadByParentId({
        "json": dicJson,
        "length": 19,
        "func": function () {
            //查询完字典后初始化数据.
            initPageData(data)
        },
        "isDefault": false
    });
}

function init(scspId) {
    $.ajax({
        url : credit.baseUrl + "/credit/"+scspId,
        type : "get",
        dataType: "json",
        contentType: "application/json",
        success: function (data) {
            if(data.code == 200){
            	initDic(data.data);
            }else{
                layer.msg(data.message);
            }
        }
    });

}
//填充input框数据
function setInputVal(data) {
	for(var x in data){
		if(yunSetVal.ifnull(data[x])) continue;
		var obj = $("#"+x);
		if(yunSetVal.ifnull(obj)) continue;
		$(obj).val(data[x]);
	}
}

function initPageData(result) {
    setInputVal(result);
    if(!$("#baseRate").val()){
        $("#baseRate").val(4.35);
    }
    
    //贷款期限
    var grantTerm = $("#grantTerm").val();
    if(grantTerm){
        var grantTermArr = grantTerm.split(",");
        if(grantTermArr[0] == ""){
            $("#grantTermY").val("0");
        }else{
            $("#grantTermY").val(grantTermArr[0]);
        }
        if(grantTermArr[1] == ""){
            $("#grantTermM").val("0");
        }else{
            $("#grantTermM").val(grantTermArr[1]);
        }
        if(grantTermArr[2] == ""){
            $("#grantTermD").val("0");
        }else{
            $("#grantTermD").val(grantTermArr[2]);
        }
    }
    //利率调整日期
    var rateAdjustDate = $("#rateAdjustDate").val();
    if(rateAdjustDate){
        var rateAdjustDateArr = rateAdjustDate.split(",");
        $("#rateAdjustDateM").val(rateAdjustDateArr[0]);
        $("#rateAdjustDateD").val(rateAdjustDateArr[1]);
    }
    //担保方式
    var guaranteeWay = $("#guaranteeWay").val();
    if(guaranteeWay.indexOf("01")>-1){
        $("#credit").prop("checked","true");
    }
    if(guaranteeWay.indexOf("02")>-1){
        $("#guarantee").prop("checked","true");
    }
    if(guaranteeWay.indexOf("03")>-1){
        $("#mortgage").prop("checked","true");
    }
    if(guaranteeWay.indexOf("04")>-1){
        $("#pledge").prop("checked","true");
    }
    //月利率
    if(!($("#executeRate").val())){
        $("#executeRate").val($("#baseRate").val());
    }
    var executeRate = $("#executeRate").val();
    $("#monthRate").val(parseFloat((parseFloat(executeRate)*10/12)).toFixed(2));

    var gracePeriodWay = $("#gracePeriodWay").val();//宽限期方式
    if(gracePeriodWay == "0" || gracePeriodWay == "2"){ // 无宽限期 || 宽限至月底 则宽限期天数为空
        $("#gracePeriod").val("");
        $("#gracePeriod").attr("disabled","disabled");
    }

    var repaymentWay = $("#repaymentWay").val();//还款方式
    if(repaymentWay == "3"){ // 一次性利随本清
        $("#repaymentInterval").attr("disabled","disabled");
    }

    var defaultInterestFloatWay = $("#defaultInterestFloatWay").val();//罚息浮动选项
    if(defaultInterestFloatWay == "0"){ // 固定罚息率
        $("#defaultInterestFloat").attr("readonly","readonly");
        var defaultInterestRate = $("#defaultInterestRate").val();
        if(!defaultInterestRate){
            $("#defaultInterestRate").val($("#executeRate").val());
        }
    }

    var rateCycle = $("#rateCycle").val();//利率调整方式
    if(rateCycle != "3"){ // 部不为指定日期调整时
        $("#rateAdjustDateM").attr("disabled","true");
        $("#rateAdjustDateD").attr("disabled","true");
    }
    //还款日确定方式
    if($("#repaymentDateWay").val() == "0"){
        $("#repaymentDate").attr("readonly","readonly");
    }
    //行业投向
    $("#hytx1").val(result.hytxs[0]);
    $("#hytx2").val(result.hytxs[1]);
    $("#hytx3").val(result.hytxs[2]);
    $("#hytx4").val(result.hytxs[3]);
    $("#hytx5").val(result.hytxs[4]);
    //贷款种类
    $("#loanType1").val(result.loanTypes[0]);
    $("#loanType2").val(result.loanTypes[1]);
}

//Date转String
function formatDate(d) {
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
//时间相加
function DateAdd(interval, number, date) {
    switch (interval) {
        case "y": {
            date.setFullYear(date.getFullYear() + parseInt(number));
            return date;
            break;
        }
        case "m": {
            date.setMonth(date.getMonth() + parseInt(number));
            return date;
            break;
        }
        case "d": {
            date.setDate(date.getDate() + parseInt(number));
            return date;
            break;
        }
        default: {
            return date;
            break;
        }
    }
}
//校验正整数 校验月份<12  日期<30
function intValidate(value,type) {
    value = parseInt(value);
    var regex = /^\+?[0-9][0-9]*$/;
    if(!regex.test(value)){
        return false;
    }
    switch (type){
        case "y":
            if(value < 0 || value > 99)
                return false;
            return true
        case "m":
            if(value < 0 ||value > 11)
                return false;
            return true;
        case "d":
            if(value < 0 ||value > 30)
                return false;
            return true;
        default:
            return true;
    }
    return true;
}

//校验正整数 校验月份<12  1、3、5、7、8、10、12日期(1~31) 2(1~28) 4、6、9、11（1~30）
function intValidateMd(mvalue,dvalue,type) {
    switch (type){
        case "m":
            if(mvalue < 1 ||mvalue > 12){
            	msg="月份需要在1~12之间"
                return false;
            }
            return true;
        case "d":
        	if(mvalue==1||mvalue==3||mvalue==5||mvalue==7||mvalue==8||mvalue==10||mvalue==12){
        		if(dvalue < 1 ||dvalue > 31){
        			msg="日需要在1~31之间"
                    return false;
        		}
        	}else if(mvalue==2){
        		if(dvalue < 1 ||dvalue > 28){
        			msg="日需要在1~28之间"
                    return false;
        		}
        	}else{
        		if(dvalue < 1 ||dvalue > 30){
        			msg="日需要在1~30之间"
                    return false;
        		}
        	}
        	return true;
        default:
            return true;
    }
    return true;
}
//设置基准利率
function setBaseRate(){
	var loanType=$("#loanType2").val();
	var grantTermY=$("#grantTermY").val();	
	if(grantTermY<=1){
		$("#baseRate").val("4.35");
	}else if(grantTermY<=5){
		$("#baseRate").val("4.75");
	}else{
		$("#baseRate").val("4.90");
	}  
}

/*验证和联动变动事件绑定*/
function eventBind(){
    //宽限期
    $("#gracePeriodWay").change(function () {
        var gracePeriodWay = $("#gracePeriodWay").val();//宽限期方式
        if(gracePeriodWay == "0" || gracePeriodWay == "2"){ // 无宽限期 || 宽限至月底 则宽限期天数为空
            $("#gracePeriod").val("");
            $("#gracePeriod").attr("disabled","disabled");
        }else{
            $("#gracePeriod").removeAttr("disabled");
        }
    });
    $("#loanType2").on("change", function () {
    	setBaseRate();//设置基准利率
    });
    //贷款期限
    $("#grantTermY,#grantTermM,#grantTermD").change(function () {
        var grantTermY = $("#grantTermY").val();
        var grantTermM = $("#grantTermM").val();
        var grantTermD = $("#grantTermD").val();
        var startDate = $("#startDate").val();
        var loanType=$("#loanType2").val();      
        var array = startDate.split("-");
        var date = new Date(array[0],array[1]-1,array[2]);
        if(grantTermY){
            if(intValidate(grantTermY,"y")){
                DateAdd("y",grantTermY,date);
            }else{
                layer.msg("年份需在0-99之间！");
                $("#grantTermY").val(0);
                return false;
            }
        }
        if(grantTermM){
            if(intValidate(grantTermM,"m")){
                DateAdd("m",grantTermM,date);
            }else{
                layer.msg("月份需在0-11之间！");
                $("#grantTermM").val(0);
                return false;
            }
        }
        if(grantTermD){
            if(intValidate(grantTermD,"d")){
                DateAdd("d",grantTermD,date);
            }else{
                layer.msg("日期需在0-30之间！");
                $("#grantTermD").val(0);
                return false;
            }
        }          
        if(startDate){
        	$("#endDate").val( formatDate(date));
        }else{
        	$("#endDate").val("");
        }
        if(loanType){
        	setBaseRate();//设置基准利率
        }
    });
    //还款方式为:3-一次性利随本清 还款间隔为:6-一次性还款  还款方式为其他项时还款间隔不能为一次性还款
    $("#repaymentWay").change(function () {
        var repaymentWay = $("#repaymentWay").val();//还款方式
        if(repaymentWay == "3"){
            $("#repaymentInterval").append("<option value='6' selected>一次性还款</option>");
            $("select[name=repaymentInterval]").attr("disabled","true");
        }else{
            $("#repaymentInterval").removeAttr("disabled");
            $("#repaymentInterval option[value='6']").remove();  //删除Select中Value='6'的Option
        }
    });
    //还款日确定方式为 1：指定还款日时 还款日期必填    为0：借款日为还款日时回显
    $("#repaymentDateWay").change(function () {
        var repaymentDateWay = $("#repaymentDateWay").val();//还款日确定方式
        if(repaymentDateWay == "0"){
            var startDate = $("#startDate").val();
            var array = startDate.split("-");
            if(array[2].indexOf("0") == 0){
                $("#repaymentDate").val(array[2].charAt(1));
            }else{
                $("#repaymentDate").val(array[2]);
            }
            $("#repaymentDate").attr("readonly","readonly");
        }else{
            $("#repaymentDate").val("");
            $("#repaymentDate").removeAttr("readonly");
        }
    });
    //利率调整方式为3：每年指定日期调整时，利率调整日期为必填
    $("#rateCycle").change(function () {
        var rateCycle = $("#rateCycle").val();//利率调整方式
        if(rateCycle != "3"){
            $("#rateAdjustDateM").val("");
            $("#rateAdjustDateD").val("");
            $("#rateAdjustDateM,#rateAdjustDateD").attr("disabled","true");
        }else {
            $("#rateAdjustDateM,#rateAdjustDateD").removeAttr("disabled")
        }
    });
    //行业投向
    $("#hytx1").on("change", function () {
        $("#hytx2").html("<option value=''>-请选择-</option>");
        $("#hytx3").html("<option value=''>-请选择-</option>");
        $("#hytx4").html("<option value=''>-请选择-</option>");
        $("#hytx5").html("<option value=''>-请选择-</option>");
    });
    $("#hytx2").on("change", function () {
        $("#hytx3").html("<option value=''>-请选择-</option>");
        $("#hytx4").html("<option value=''>-请选择-</option>");
        $("#hytx5").html("<option value=''>-请选择-</option>");
    });
    $("#hytx3").on("change", function () {
        $("#hytx4").html("<option value=''>-请选择-</option>");
        $("#hytx5").html("<option value=''>-请选择-</option>");
    });
    $("#hytx4").on("change", function () {
        $("#hytx5").html("<option value=''>-请选择-</option>");
    });
    //执行利率（%）=（基准利率+利率浮动值）*（1+利率浮动率）
    //月利率(‰) = 执行利率/12
    /*$("#rateFloat,#rateFloatValue").on("input propertyValue",function () {*/
    $("#rateFloat,#rateFloatValue").on("blur",function () {
        var rateFloat = $("#rateFloat").val(); //利率浮动率
        var rateFloatValue = $("#rateFloatValue").val(); //利率浮动值
        var regex = /^(-)?([0-9]{1,3})(\.\d{1,2}){0,1}$/;
        if(!rateFloat){
            rateFloat = 0;
        }else {
            if (!regex.test($("#rateFloat").val())) {
                layer.msg("利率浮动率填写有误！");
                return false;
            }
        }
        if(!rateFloatValue){
            rateFloatValue = 0;
        }else {
            if (!regex.test($("#rateFloatValue").val())) {
                layer.msg("利率浮动值填写有误！");
                return false;
            }
        }
        var baseRate = $("#baseRate").val();//基准利率
        var executeRate = parseFloat((parseFloat(baseRate) + parseFloat(rateFloatValue))*(1 + parseFloat(rateFloat)/100)).toFixed(2);
        $("#executeRate").val(executeRate);
        $("#monthRate").val(parseFloat((parseFloat(executeRate)*10/12)).toFixed(2));
        //罚息利率 = 执行利率*（1+罚息浮动率）
        var defaultInterestFloat = $("#defaultInterestFloat").val(); //罚息浮动率
        if(defaultInterestFloat){
            var defaultInterestRate = parseFloat(parseFloat(executeRate)*(1+parseFloat(defaultInterestFloat)/100)).toFixed(2);
            $("#defaultInterestRate").val(defaultInterestRate);
        }else{
            $("#defaultInterestRate").val(executeRate);
        }
    });
    //罚息浮动选项为0-固定罚息率时，罚息浮动率为0，为1-按合同利率浮动时，罚息浮动率手动输入
    $("#defaultInterestFloatWay").change(function () {
        var defaultInterestFloatWay = $("#defaultInterestFloatWay").val();
        if(defaultInterestFloatWay == "0"){
            $("#defaultInterestFloat").val(0);
            var executeRate = $("#executeRate").val();
            //罚息利率=执行利率*（1+罚息浮动率）
            //若罚息浮动选项为0：固定罚息率，则罚息浮动率为0  此时罚息利率=执行利率
            if(executeRate){
                $("#defaultInterestRate").val(executeRate);
            }
            $("#defaultInterestFloat").attr("readonly","readonly");
        }else {
            $("#defaultInterestFloat").removeAttr("readonly");
        }
    });
    //罚息浮动率变化  改变罚息利率
    $('#defaultInterestFloat').on('blur', function() {
        /*$('#result').html($(this).val().length + ' characters');*/
        var defaultInterestFloat = $("#defaultInterestFloat").val(); //罚息浮动率
        var regex = /^(-)?([0-9]{1,3})(\.\d{1,2}){0,1}$/;
        if(defaultInterestFloat){
            if (!regex.test(defaultInterestFloat)) {
                layer.msg("罚息浮动率填写有误！");
                return false;
            }
        }

        //罚息利率 = 执行利率*（1+罚息浮动率）
        var executeRate = $("#executeRate").val();
        if(defaultInterestFloat && executeRate){
            var defaultInterestRate = parseFloat(parseFloat(executeRate)*(1+parseFloat(defaultInterestFloat)/100)).toFixed(2);
            $("#defaultInterestRate").val(defaultInterestRate);
        }
    });
}

/**检查必填项, true可以进行保存, false不可以进行保存.*/
function checkRequiredItems() {
	//还款日确定方式
	if($("#repaymentDateWay").val() == ""||$("#repaymentDateWay").val()==null){
		document.getElementById("repaymentDateWay").scrollIntoView(false);
        layer.tips("请选着还款日确定方式", $("#repaymentDateWay"), {tips: [1, '#78BA32']});
        return false;
	}
    //校验还款日
    if($("#repaymentDateWay").val() != "0"){
        var regex = /^\+?[1-9][0-9]*$/;
        //还款日
        if ($("#repaymentDate").val() == '' || $("#repaymentDate").val() == null) {
        	document.getElementById("repaymentDate").scrollIntoView(false); 
            layer.tips("还款日不能为空！", $("#repaymentDate"), {tips: [1, '#78BA32']});
            return false;
        }else if(!regex.test($("#repaymentDate").val())){
            document.getElementById("repaymentDate").scrollIntoView(false);
            layer.tips("还款日为正整数", $("#repaymentDate"), {tips: [1, '#78BA32']});
            return false;
        }else {
            var repaymentDate = parseInt($("#repaymentDate").val());
            if(repaymentDate > 28 ){
                document.getElementById("repaymentDate").scrollIntoView(false);
                layer.tips("还款日范围只能在1-28之间", $("#repaymentDate"), {tips: [1, '#78BA32']});
                return false;
            }
        }
    }
    //校验利率调整日期  //利率调整方式为3：每年指定日期调整时，利率调整日期为必填
    if($("#rateCycle").val() == "3"){
        if($("#rateAdjustDateM").val() == "" || $("#rateAdjustDateM").val() == null || $("#rateAdjustDateD").val() == "" || $("#rateAdjustDateD").val() == null){
            document.getElementById("rateAdjustDateM").scrollIntoView(false);
            layer.tips("利率调整日期不能为空", $("#rateAdjustDateM"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    //利率调整日期  月
    if($("#rateAdjustDateM").val()){
        if(!intValidateMd($("#rateAdjustDateM").val(),null,"m")){
            layer.tips(msg, $("#rateAdjustDateM"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    //利率调整日期  日
    if($("#rateAdjustDateD").val()){
    	if(!$("#rateAdjustDateM").val()){
    		layer.tips("请输入利率调整日期的月份！", $("#rateAdjustDateM"), {tips: [1, '#78BA32']});   		
    	}
        if(!intValidateMd($("#rateAdjustDateM").val(),$("#rateAdjustDateD").val(),"d")){
            layer.tips(msg, $("#rateAdjustDateD"), {tips: [1, '#78BA32']});
            return false;
        }
    }

    //校验罚息浮动率
    if($("#defaultInterestFloatWay").val() == "1"){ //按合同利率浮动
        if($("#defaultInterestFloat").val() == "" || $("#defaultInterestFloat").val() == null ){
            document.getElementById("defaultInterestFloat").scrollIntoView(false);
            layer.tips("罚息浮动率不能为空", $("#defaultInterestFloat"), {tips: [1, '#78BA32']});
            return false;
        }
        var regex = /^(-)?([0-9]{1,3})(\.\d{1,2}){0,1}$/;
        if (!regex.test($("#defaultInterestFloat").val())) {
            layer.tips("罚息浮动率填写有误", $("#defaultInterestFloat"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    
    //利率浮动率
    if($("#rateFloat").val()){
        var regex = /^(-)?([0-9]{1,3})(\.\d{1,2}){0,1}$/;
        if (!regex.test($("#rateFloat").val())) {
            layer.tips("利率浮动率填写有误", $("#rateFloat"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    //利率浮动值
    if($("#rateFloatValue").val()){
        var regex = /^(-)?([0-9]{1,3})(\.\d{1,2}){0,1}$/;
        if (!regex.test($("#rateFloatValue").val())) {
            layer.tips("利率浮动值填写有误", $("#rateFloatValue"), {tips: [1, '#78BA32']});
            return false;
        }
    }

    //放款金额
    if ($("#grantMoney").val() == '' || $("#grantMoney").val() == null) {
    	document.getElementById("grantMoney").scrollIntoView(false); 
        layer.tips("放款金额不能为空", $("#grantMoney"), {tips: [1, '#78BA32']});
        return false;
    }

    if($("#grantMoney").val()){
        var regex = /^(-)?([0-9]{1,12})(\.\d{1,2}){0,1}$/;
        if (!regex.test($("#grantMoney").val())) {
            layer.tips("放款金额填写有误", $("#grantMoney"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    //罚息浮动选项
    if($("#defaultInterestFloatWay").val()==null||$("#defaultInterestFloatWay").val()==''){
    	document.getElementById("defaultInterestFloatWay").scrollIntoView(true); 
    	layer.tips("请选择罚息浮动选项", $("#defaultInterestFloatWay"), {tips: [1, '#78BA32']});
        return false;
    }
    if(credit.stat=='4'){
    	//放款日期
        if ($("#startDate").val() == '' || $("#startDate").val() == null) {
        	document.getElementById("startDate").scrollIntoView(false); 
            layer.tips("放款日期不能为空", $("#startDate"), {tips: [1, '#78BA32']});
            return false;
        }
        //到期日期
        if ($("#endDate").val() == '' || $("#endDate").val() == null) {
        	document.getElementById("endDate").scrollIntoView(false); 
            layer.tips("到期日期不能为空！", $("#endDate"), {tips: [1, '#78BA32']});
            return false;
        } 

        var num = /^\d*$/;//全数字
        //开头六位
        var strBin = "10,18,29,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
        //放款账户
        if ($("#grantAccount").val() == '' || $("#grantAccount").val() == null) {
        	document.getElementById("grantAccount").scrollIntoView(true); 
            layer.tips("放款账户不能为空！", $("#grantAccount"), {tips: [1, '#78BA32']});
            return false;
        }else if($("#grantAccount").val().length < 16 || $("#grantAccount").val().length > 19){
            layer.tips("放款账户长度必须在16到19之间！", $("#grantAccount"), {tips: [1, '#78BA32']});
            return false;
        }else if(!num.exec($("#grantAccount").val())){
            layer.tips("放款账户必须为全数字！", $("#grantAccount"), {tips: [1, '#78BA32']});
            return false;
        }/*else if(strBin.indexOf($("#grantAccount").val().substring(0, 2)) == -1){
            layer.tips("银行卡号开头6位不符合规范！", $("#grantAccount"), {tips: [1, '#78BA32']});
            return false;
        }*/
        // else if(!luhnCheck($("#grantAccount").val())){
        //     layer.tips("银行卡号填写有误，请检查！", $("#grantAccount"), {tips: [1, '#78BA32']});
        //     return false;
        // }
        //还款账户
        if ($("#repaymentAccount").val() == '' || $("#repaymentAccount").val() == null) {
        	document.getElementById("repaymentAccount").scrollIntoView(true); 
            layer.tips("还款账户不能为空！", $("#repaymentAccount"), {tips: [1, '#78BA32']});
            return false;
        }else if($("#repaymentAccount").val().length < 16 || $("#repaymentAccount").val().length > 19){
            layer.tips("还款账户长度必须在16到19之间！", $("#repaymentAccount"), {tips: [1, '#78BA32']});
            return false;
        }else if(!num.exec($("#repaymentAccount").val())){
            layer.tips("还款账户必须为全数字！", $("#repaymentAccount"), {tips: [1, '#78BA32']});
            return false;
        }/*else if(strBin.indexOf($("#repaymentAccount").val().substring(0, 2)) == -1){
            layer.tips("还款账户开头6位不符合规范！", $("#repaymentAccount"), {tips: [1, '#78BA32']});
            return false;
        }*/
        // else if(!luhnCheck($("#repaymentAccount").val())){
        //     layer.tips("银行卡号填写有误，请检查！", $("#repaymentAccount"), {tips: [1, '#78BA32']});
        //     return false;
        // }
    }
    
    //还款方式
    if ($("#repaymentWay").val() == '' || $("#repaymentWay").val() == null) {
    	document.getElementById("repaymentWay").scrollIntoView(false); 
        layer.tips("还款方式不能为空！", $("#repaymentWay"), {tips: [1, '#78BA32']});
        return false;
    }
    //还款间隔
    if ($("#repaymentInterval").val() == '' || $("#repaymentInterval").val() == null) {
    	document.getElementById("repaymentInterval").scrollIntoView(false); 
        layer.tips("还款间隔不能为空！", $("#repaymentInterval"), {tips: [1, '#78BA32']});
        return false;
    }
   
    //罚息利率
    if ($("#defaultInterestRate").val() == '' || $("#defaultInterestRate").val() == null) {
    	document.getElementById("defaultInterestRate").scrollIntoView(false); 
        layer.tips("罚息利率不能为空！", $("#defaultInterestRate"), {tips: [1, '#78BA32']});
        return false;
    }
    //单复率标志
    if ($("#singleRateSign").val() == '' || $("#singleRateSign").val() == null) {
    	document.getElementById("singleRateSign").scrollIntoView(false); 
        layer.tips("单复率标志不能为空！", $("#singleRateSign"), {tips: [1, '#78BA32']});
        return false;
    }
    //借款人属性
    if ($("#loanerAttribute").val() == '' || $("#loanerAttribute").val() == null) {
    	document.getElementById("loanerAttribute").scrollIntoView(false); 
        layer.tips("借款人属性不能为空！", $("#loanerAttribute"), {tips: [1, '#78BA32']});
        return false;
    }

    //宽限期方式
    if ($("#gracePeriodWay").val() == '' || $("#gracePeriodWay").val() == null) {
        layer.msg("宽限期方式不能为空！");
        return false;
    }
    //宽限期天数
    if($("#gracePeriodWay").val() == "1"){//宽限期方式为  按日计算
        if ($("#gracePeriod").val() == '' || $("#gracePeriod").val() == null) {
        	document.getElementById("gracePeriod").scrollIntoView(true);
            layer.tips("宽限期方式为“按日计算”时，宽限期天数不能为空！", $("#gracePeriod"), {tips: [1, '#78BA32']});
            return false;
        }
        if($("#gracePeriod").val()){
            var regex = /^\+?[1-9][0-9]*$/;
            if(!regex.test($("#gracePeriod").val())){
                layer.tips("宽限期天数为正整数！", $("#gracePeriod"), {tips: [1, '#78BA32']});
                return false;
            }
        }
    }
    //行业投向
    if ($("#hytx1").val() == null ||$("#hytx1").val() == '') {
    	document.getElementById("hytx1").scrollIntoView(false); 
        layer.tips("行业投向第一项不能为空！", $("#hytx1"), {tips: [1, '#78BA32']});
        return false;
    }
    if ($("#hytx2").val() == null ||$("#hytx2").val() == '') {
    	document.getElementById("hytx2").scrollIntoView(false); 
        layer.tips("行业投向第二项不能为空！", $("#hytx2"), {tips: [1, '#78BA32']});
        return false;
    }
    if(document.getElementById("hytx3").options.length!= 1){
    	if ($("#hytx3").val() == null ||$("#hytx3").val() == '') {
        	document.getElementById("hytx3").scrollIntoView(false); 
            layer.tips("行业投向第三项不能为空！", $("#hytx3"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    if(document.getElementById("hytx4").options.length!= 1){
    	if ($("#hytx4").val() == null ||$("#hytx4").val() == '') {
        	document.getElementById("hytx4").scrollIntoView(false); 
            layer.tips("行业投向第四项不能为空！", $("#hytx4"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    if(document.getElementById("hytx5").options.length!= 1){
    	if ($("#hytx5").val() == null ||$("#hytx5").val() == '') {
        	document.getElementById("hytx5").scrollIntoView(false); 
            layer.tips("行业投向第五项不能为空！", $("#hytx5"), {tips: [1, '#78BA32']});
            return false;
        }
    }
    //贷款种类
    if ($("#loanType1").val() == null ||$("#loanType1").val() == '') {
        document.getElementById("loanType1").scrollIntoView(false);
        layer.tips("贷款品种第一项不能为空！", $("#loanType1"), {tips: [1, '#78BA32']});
        return false;
    }
    if ($("#loanType2").val() == null ||$("#loanType2").val() == '') {
        document.getElementById("loanType2").scrollIntoView(false);
        layer.tips("行贷款品种第二项不能为空！", $("#loanType2"), {tips: [1, '#78BA32']});
        return false;
    }

    //利率调整方式
    if ($("#rateCycle").val() == '' || $("#rateCycle").val() == null) {
    	document.getElementById("rateCycle").scrollIntoView(true); 
        layer.tips("利率调整方式不能为空！", $("#rateCycle"), {tips: [1, '#78BA32']});
        return false;
    }
    //基准利率
    if ($("#baseRate").val() == '' || $("#baseRate").val() == null) {
    	document.getElementById("baseRate").scrollIntoView(true); 
        layer.tips("基准利率不能为空！", $("#baseRate"), {tips: [1, '#78BA32']});
        return false;
    }
    //执行利率
    if ($("#executeRate").val() == '' || $("#executeRate").val() == null) {
    	document.getElementById("executeRate").scrollIntoView(true); 
        layer.tips("执行利率不能为空！", $("#executeRate"), {tips: [1, '#78BA32']});
        return false;
    }
    //贷款用途
    if ($("#loanPurpose").val() == '' || $("#loanPurpose").val() == null) {
    	document.getElementById("loanPurpose").scrollIntoView(true); 
    	  layer.tips("贷款用途不能为空！", $("#loanPurpose"), {tips: [1, '#78BA32']});
        return false;
    }
    if ($("#loanPurposeDetail").val() == '' || $("#loanPurposeDetail").val() == null) {
        layer.tips("贷款用途描述不能为空！", $("#loanPurposeDetail"), {tips: [1, '#78BA32']});
        return false;
    }
    if($("#grantTermY").val().trim() == ''){
    	$("#grantTermY").val("0");
    }
    if($("#grantTermM").val().trim() == ''){
    	$("#grantTermM").val("0");
    }
    if($("#grantTermD").val().trim() == ''){
    	$("#grantTermD").val("0");
    }
    if($("#grantTermY").val() == '0' && $("#grantTermM").val() == '0' && $("#grantTermD").val() == '0'){
    	document.getElementById("grantTermD").scrollIntoView(false); 
        layer.tips("贷款期限不能小于一天！", $("#grantTerms"), {tips: [1, '#78BA32']});
        return false;
    }


    return true;
}
//获取时间
function initTimePickers(inputId) {
    $("#" + inputId).datepicker({
        format : 'yyyy-mm-dd',
        language : 'zh-CN',
        minDate:0,
        autoclose:true //选择日期后自动关闭

    });
}
// 0-99年
function test(num)
{
    var reg = /^((?!0)\d{1,2}|99)$/;
    if(!num.match(reg)){
        return false;
    }else{
        return true;
    }
}
//银行卡号Luhn校验算法
//luhn校验规则：16位银行卡号（19位通用）:
//1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
//2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
//3.将加法和加上校验位能被 10 整除。
// bankno为银行卡号
function luhnCheck(bankno) {
    var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）
    var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
    var newArr = new Array();
    for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i, 1));
    }
    var arrJiShu = new Array(); //奇数位*2的积 <9
    var arrJiShu2 = new Array(); //奇数位*2的积 >9
    var arrOuShu = new Array(); //偶数位数组
    for (var j = 0; j < newArr.length; j++) {
        if ((j + 1) % 2 == 1) { //奇数位
            if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
            else arrJiShu2.push(parseInt(newArr[j]) * 2);
        } else //偶数位
            arrOuShu.push(newArr[j]);
    }

    var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
    var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
    for (var h = 0; h < arrJiShu2.length; h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
    }

    var sumJiShu = 0; //奇数位*2 < 9 的数组之和
    var sumOuShu = 0; //偶数位数组之和
    var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
    var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
    var sumTotal = 0;
    for (var m = 0; m < arrJiShu.length; m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
    }

    for (var n = 0; n < arrOuShu.length; n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
    }

    for (var p = 0; p < jishu_child1.length; p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
    }
    //计算总和
    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

    //计算luhn值
    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
    var luhn = 10 - k;
    if (lastNum == luhn) {
        $("#banknoInfo").html("luhn验证通过");
        return true;
    } else {
        $("#banknoInfo").html("银行卡号必须符合luhn校验");
        return false;
    }
}

//打印
function myprint() {
	$("#button").hide();
    setTimeout(function () {
    	$("#button").show();  
    }, 500)
    window.print();
    winname.document.execCommand('print'); //打印
    winname.close();
}




